package midone.exchangeskill.utils;

import android.util.ArrayMap;
import android.util.Pair;

import java.util.HashMap;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

public class RxBus {
    private static RxBus mRxBus = null;
    /**
     * PublishSubject只会把在订阅发生的时间点之后来自原始Observable的数据发射给观察者
     */

    private Subject<Object, Object> mRxBusObserverable = new SerializedSubject<>(PublishSubject.create());

    public static synchronized RxBus getInstance() {
        if (mRxBus == null) {
            mRxBus = new RxBus();
        }
        return mRxBus;
    }

    /**
     * 如果有订阅者 则发送消息
     *
     * @param o
     */
    public void post(Object o) {
        if (this.hasObservers()) {
            mRxBusObserverable.onNext(o);
        }
    }


    public Observable<Object> toObserverable() {
        return mRxBusObserverable;
    }

    /**
     * 判断是否有订阅者
     */
    public boolean hasObservers() {
        return mRxBusObserverable.hasObservers();
    }

    /**
     * RX bus消息
     */
    public static class RxMessageEvent {
        String action;
        ArrayMap<String,Object> arrayMap;
        HashMap<String, Object> map;
        Object object;
        Pair<Object,Object> objectPair;

        public RxMessageEvent(String action, Pair<Object, Object> objectPair) {
            this.action = action;
            this.objectPair = objectPair;
        }


        public RxMessageEvent(String action, ArrayMap<String, Object> arrayMap) {
            this.action = action;
            this.arrayMap = arrayMap;
        }

        public Object getObject() {
            return object;
        }

        public void setObject(Object object) {
            this.object = object;
        }

        public RxMessageEvent(String action, Object object) {
            this.action = action;
            this.object = object;
        }

        public RxMessageEvent(String action) {
            this.action = action;
        }

        public RxMessageEvent(String action, HashMap<String, Object> object) {
            this.action = action;
            this.map = object;
        }


        public String getAction() {
            return action;
        }

        public void setAction(String action) {
            this.action = action;
        }

        public HashMap<String, Object> getMap() {
            return map;
        }

    }
}